var _rootWindow = $(window);
var _winWidth = _rootWindow.width();
var _winHeight = _rootWindow.height();

var footer = {
  toTop: function () {
    var btn = document.querySelector(".totop");
    if (btn) {
      btn.addEventListener("click", function () {
        if (_rootWindow.cscroll) {
          _rootWindow.cscroll.scrollTo("top");
        } else {
          window.scrollTo({
            top: 0,
            behavior: "smooth",
          });
        }
      });
    }
  },
  _init: function () {
    this.toTop();
  },
};
var recruitListPage = {
  accordion: function () {
    var reclTitle = document.querySelectorAll(".recl-title");
    if (!reclTitle[0]) return;
    Array.from(reclTitle, function (item) {
      item.addEventListener("click", function () {
        recruitListPage.accordionIsClick = true;
        var parentDom = this.parentNode;
        parentDom.classList.toggle("active");
        parentDom.addEventListener("transitionend", function () {
          // 初始化滚动
          _rootWindow.cscroll?.update();
        });
      });
    });
  },
  
  _init: function () {
    this.accordion();
  },
};
var header = {
  acordionReasizeSize: function () {
    if (typeof ResizeObserver === "undefined") return;
    var rec = document.querySelector(".resize-container");
    if (!rec) return;
    const resizeObserver = new ResizeObserver(function (entries) {
      _rootWindow.cscroll && _rootWindow.cscroll.update();
    });

    resizeObserver.observe(rec);
  },
  imagesLoadedProgress/**未使用 */: function () {
    var cont = $("#container");
    if (!cont[0] || typeof imagesLoaded === "undefined") return;
    header.timer = setInterval(function () {
      _rootWindow.cscroll.update();
    }, 5000);
    cont
      .imagesLoaded()
      .done(function (instance, image) {
        console.log(instance);
        clearInterval(header.timer);
      })
      .fail(function () {
        clearInterval(header.timer);
      });
  },
  domAnimation: function () {
    if (!_rootWindow.cscroll || typeof TimelineMax === "undefined") {
      return;
    }

    _rootWindow.cscroll.on("call", function (...args) {
      // recruit-list页面手风琴点击过  也不进入。因为手风琴点击会重新触发 平滑滚动的upload事件，导致 该页面的所有call事件重新再次触发一边
      if (recruitListPage.accordionIsClick) return;
      var gsap = new TimelineMax();
      var target = args[2];
      var a = args[0];
      if (a === "topCurA") {
        gsap.from(
          $(target.target),
          0.3,
          {
            css: {
              transform: "translateY(100px)",
              opacity: 0,
            },
            onComplete: function(){
              $(target.target).css({
                opacity: 1,
                tranfrom: "translateY(0)"
              })
            }
          },
          0.2
        );
      }
      if (a === "topA") {
        var doms = $(target.target).find("[data-topA]");
        gsap.staggerFrom(
          doms,
          0.3,
          {
            css: {
              transform: "translateY(100px)",
              opacity: 0,
            },
            onComplete: function(){
              $(target.target).css({
                opacity: 1,
                tranfrom: "translateY(0)"
              })
            }
          },
          0.2
        );
      }
      if (a === "topA2") {
        var doms = $(target.target).find("[data-topA]");
        gsap.staggerFrom(
          doms,
          0.2,
          {
            css: {
              transform: "translateY(50px)",
              opacity: 0,
            },
          },
          0.1
        );
      }
      if (a === "opacityA") {
        var opacityA = $(target.target).find("[data-opacityA]");
        var toLeftA = $(target.target).find("[data-toLeftA]");
        gsap.from(opacityA, 0.3, {
          css: {
            opacity: 0,
          },
          onComplete: function () {
            gsap.to(toLeftA, 0.3, {
              css: {
                left: 0,
              },
            });
          },
        });
      }
    });
  },
  // 全栈的平滑滚动
  locomotiveScroll: function () {
    var scrolldom = document.querySelector("[data-scroll-container]");
    if (!scrolldom || typeof LocomotiveScroll === "undefined") return;
    _rootWindow.cscroll = new LocomotiveScroll({
      el: scrolldom,
      smooth: true,
      scrollFromAnywhere: true,
      reloadOnContextChange: true,
      smartphone: {
        breakpoint: 0,
        smooth: true,
        lerp: 0.8,
        getSpeed: true,
      },
      tablet: {
        breakpoint: 0,
        smooth: true,
        lerp: 0.8,
        getSpeed: true,
      },
    });
  },

  // 下拉选择框
  dataList/**未使用 */: function () {
    var datalist = document.querySelectorAll(".cl-select");
    if (!datalist[0]) return;
    datalist.forEach(function (item) {
      item.addEventListener("click", function (e) {
        stopBubble(e);
        item.classList.add("on");
      });
    });
    var selectlist = document.querySelectorAll(".cl-select-list");
    if (!selectlist[0]) return;
    selectlist.forEach(function (item) {
      item.addEventListener("click", function (e) {
        stopBubble(e);
        var target = e.target;
        if (target.tagName === "LI") {
          target.parentNode.parentNode.classList.remove("on");
          target.parentNode.previousElementSibling.value = target.innerText;
        }
      });
    });

    document.addEventListener("click", function (e) {
      selectlist.forEach(function (item) {
        item.parentNode.classList.remove("on");
      });
    });
  },
  // 侧边栏跟随滚动条
  asideScroll: function (el_class) {
    var aside = document.getElementById("aside");
    if (!_rootWindow.cscroll || !aside) return;
    _rootWindow.cscroll.on("scroll", (args) => {
      var scrollY = args.scroll.y;
      if (typeof args.currentElements["hey"] === "object") {
        var top = args.currentElements["hey"].top;
        var y = scrollY - top <= 0 ? 0 : scrollY - top;
        aside.style.transform = `translateY(${y}px)`;
      }
      if (header.isclickable) return; // 1.1 用于去除插件 滚动时联动效果

      for (var name in args.currentElements) {
        var item = args.currentElements[name];
        if (name !== "hey" && item.class === "section" && scrollY >= item.top) {
          header.asideItemInit(el_class, item.el.id);
        }
      }
    });
  },
  // 侧边栏点击滚动
  asideClickToTarget: function (el_class) {
    var aside = document.getElementById("aside");
    if (!_rootWindow.cscroll || !aside) return;
    aside.addEventListener("click", function (e) {
      var target = e.target;
      if (target.classList.contains(el_class.slice(1))) {
        header.isclickable = true; // 1 用于去除插件 滚动时联动效果
        header.asideItemInit(el_class);
        target.classList.add("on");
        var dom = document.getElementById(target.dataset.target);
        _rootWindow.cscroll.scrollTo(dom, {
          callback: function () {
            header.isclickable = false;
          },
        });
      }
    });
  },
  asideItemInit: function (el_class, id) {
    var abdeItem = document.querySelectorAll(el_class);
    if (!abdeItem[0]) return;
    abdeItem.forEach(function (item, index) {
      item.classList.remove("on");
      // 用于content滚动时联动aside的focus
      if (id && item.dataset.target === id) {
        item.classList.add("on");
      }
    });
  },
  _init: function () {
    this.isclickable = false;
    this.locomotiveScroll();
    this.domAnimation();
    this.acordionReasizeSize();
  },
};

var indexPage = {
  swiperAnimate: function () {
    if (!document.querySelector(".cSwiper")) return;
    var interleaveOffset = 0.5; //视差比值

    var swiperOptions = {
      speed: 1000,
      grabCursor: true,
      loop: true,
      autoplay: true,
      watchSlidesProgress: true,
      on: {
        // 设置svg动画，跟随slider切换变更
        slideChange: function (swiper) {
          var silderLen = swiper.passedParams.loop
            ? swiper.slides.length - 2
            : swiper.slides.length;
          var xxx = $(".xxx");
          // 377 圆的周长
          xxx
            .find(".cSwiper-svg2")
            .stop()
            .css({
              "stroke-dasharray": `${
                (377 / silderLen) * (swiper.realIndex + 1)
              }, 377`,
            });
          xxx.find("span").text(swiper.realIndex + 1 + "/" + silderLen);
        },
        // swiper图片切换效果1 官网案例
        progress: function (swiper, progress) {
          for (var i = 0; i < swiper.slides.length; i++) {
            var slideProgress = swiper.slides[i].progress;
            var innerOffset = swiper.width * interleaveOffset;
            var innerTranslate = slideProgress * innerOffset;
            swiper.slides[i].querySelector(".cSwiper-inner").style.transform =
              "translate3d(" + innerTranslate + "px, 0, 0)";
          }
        },
        // swiper图片切换效果2
        touchStart: function (swiper) {
          for (var i = 0; i < swiper.slides.length; i++) {
            swiper.slides[i].style.transition = "";
          }
        },
        // swiper图片切换效果3
        setTransition: function (swiper, speed) {
          for (var i = 0; i < swiper.slides.length; i++) {
            swiper.slides[i].style.transition = speed + "ms";
            swiper.slides[i].querySelector(".cSwiper-inner").style.transition =
              speed + "ms";
          }
        },
      },
    };

    header.swiper = new Swiper(".cSwiper", swiperOptions);
  },
  fifthScreenListSwitch: function () {
    const tabs = document.querySelectorAll(".tabline-btn");

    if (!tabs[0]) return;
    tabs.forEach(function (item, index) {
      item.addEventListener("click", function () {
        tabs.forEach(function (titem, tindex) {
          titem.classList.remove("on");
          if (tindex === index) {
            titem.classList.add("on");
          }
        });
        var items = this.parentNode.nextElementSibling.children;
        Array.from(items, function (o, i) {
          $(o).hide();
          if (i === index) {
            $(o).show();
          }
        });
      });
    });
  },

  _init: function () {
    this.swiperAnimate();
    this.fifthScreenListSwitch();
  },
};
var sapPage = {
  _init: function () {
    header.asideScroll(".sap-calendar-li");
    header.asideClickToTarget(".sap-calendar-li");
  },
};
var aboutPage = {
  _init: function () {
    header.asideScroll(".abde-item");
    header.asideClickToTarget(".abde-item");
  },
};

_rootWindow.on(
  "resize",
  debounce(function () {
    // 刷新浏览器 用于初始化平滑滚动插件
    if (_rootWindow.cscroll) window.location = window.location;
  }, 500)
);

$(function () {
  header._init();
  footer._init();
  var pathname = window.location.pathname;
  indexPage._init();
  if (/about/.test(pathname)) {
    aboutPage._init();
  } else if (/recruit-list/.test(pathname)) {
    recruitListPage._init();
  } else if (/sap/.test(pathname)) {
    sapPage._init();
  }
});

// =========工具方法=============
function throttle(fn, delay) {
  // 利用闭包保存时间
  let prev = Date.now();
  return function () {
    let context = this;
    let arg = arguments;
    let now = Date.now();
    if (now - prev >= delay) {
      fn.apply(context, arg);
      prev = Date.now();
    }
  };
}

function stopBubble(e) {
  if (e.stopPropagation) {
    e.stopPropagation();
  } else {
    e.cancelBubble = true;
  }
}

function debounce(fn, delay) {
  // 利用闭包保存定时器
  let timer = null;
  return function () {
    let context = this;
    let arg = arguments;
    // 在规定时间内再次触发会先清除定时器后再重设定时器
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, arg);
    }, delay);
  };
}
